/*
 * @Author: your name
 * @Date: 2021-03-08 17:05:35
 * @LastEditTime: 2021-04-01 11:21:33
 * @LastEditors: lily
 * @Description: In User Settings Edit
 * @FilePath: \testcodeg:\work\leetcode\code\414.第三大的数.js
 */
/*
 * @lc app=leetcode.cn id=414 lang=javascript
 *
 * [414] 第三大的数
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */


// 思路：
// 需要找出三个最大的数，用三个变量存储起来，过滤掉重复的值。遍历逐步替换最大值，max => mid => min。
// 如果mid或min不存在，这说明不存在第三大的数，返回max

// 复杂度：O(n)、O(1)

var thirdMax = function (nums) {
    var max = -Infinity, second = -Infinity, third = -Infinity
    for (var i = 0; i < nums.length; i++) {
        if (nums[i] > max) {
            third = second
            second = max
            max = nums[i]
        } else if (nums[i] > second && nums[i] != max) {
            third = second
            second = nums[i]
        } else if (nums[i] > third && nums[i] != second && nums[i] != max) {
            third = nums[i]
        }
    }
    return third !== -Infinity ? third : max
};
// @lc code=end


